package service

import (
	"fanqiechaodan-blog/config"
	"fanqiechaodan-blog/dao"
	"fanqiechaodan-blog/models"
	"fanqiechaodan-blog/utils"
	"html/template"
)

func GetAllIndexInfo(slug string, page, pageSize int) (*models.HomeResponse, error) {
	// 查询所有的分类
	categorys, err := dao.GetAllCategory()
	if err != nil {
		return nil, err
	}
	var postPage []models.Post
	var count int
	if slug == "" {
		postPage, err = dao.PostPage(page, pageSize)
		if err != nil {
			return nil, err
		}
		count, err = dao.PostCount()
		if err != nil {
			return nil, err
		}
	} else {
		postPage, err = dao.PostPageBySlug(slug, page, pageSize)
		if err != nil {
			return nil, err
		}
		count, err = dao.PostCountBySlug(slug)
		if err != nil {
			return nil, err
		}
	}
	var posts []models.PostMore
	for _, post := range postPage {
		// 将内容转换成中文,首页内容只展示部分内容
		// 去除HTML标签
		contentStr := utils.StripHTML(post.Content)
		content := []rune(contentStr)
		if len(content) > 100 {
			content = content[0:100]
		}
		// 获取分类名
		categoryName, err := dao.GetCategoryNameById(post.CategoryId)
		if err != nil {
			return nil, err
		}
		userName, err := dao.GetUserNameById(post.UserId)
		if err != nil {
			return nil, err
		}
		postMore := models.PostMore{
			Pid:          post.Pid,
			Title:        post.Title,
			Slug:         post.Slug,
			Content:      template.HTML(content),
			CategoryId:   post.CategoryId,
			CategoryName: categoryName,
			UserId:       post.UserId,
			UserName:     userName,
			ViewCount:    post.ViewCount,
			Type:         post.Type,
			CreateAt:     models.DateDay(post.CreateAt),
			UpdateAt:     models.DateDay(post.UpdateAt),
		}
		posts = append(posts, postMore)
	}
	pageCount := (count-1)/pageSize + 1
	var pages []int
	for i := 1; i <= pageCount; i++ {
		pages = append(pages, i)
	}
	return &models.HomeResponse{
		Viewer:    config.Cfg.Viewer,
		Categorys: categorys,
		Posts:     posts,
		Total:     count,
		Page:      page,
		Pages:     pages,
		PageEnd:   page != pageCount,
	}, err
}
